<?php

namespace Ftt;
use Ftt\db\Connection;

/**
 * Class Application
 * @property Connection $db
 * @package Ftt
 */
class Application
{
    public $config;

    /**
     * Application constructor.
     * @param array $config
     */
    public function __construct($config)
    {
        $this->config = $config;
        Ftt::$app = $this;
    }

    public function run(){
        try{
            Route::dispatch();
        }catch (\Exception $e){
            echo '<pre>';
            echo '<h2>'.$e->getMessage().'</h2>';
            echo '<p>'.$e->getTraceAsString().'</p>';
            echo '</pre>';
            echo '<hr>';
            echo '<p>&copy Ftt 2016 v0.1</p>';
        }
    }

    /**
     * get Component by name
     * @param string $name
     * @throws Exception
     * @return mixed
     */
    public function getComponent($name){
        if(isset($this->config['components'][$name])){
            $className = $this->config['components'][$name]['class'];
            if(empty($className)){
                throw new Exception("The component \"$name\" must have a \"class\" configuration item");
            }

            if(!class_exists($className)){
                throw new Exception("The class \"$className\" not found");
            }

            $params = $this->config['components'][$name];
            unset($params['class']);

            $this->$name = new $className();

            if(!empty($params)){
                foreach($params as $attribute => $value){
                    $this->$name->$attribute = $value;
                }
            }

            return $this->$name;
        }

        return false;
    }

    public function __get($name)
    {
        $component = $this->getComponent($name);

        if($component){
            return $component;
        }

        throw new Exception("Unknown property \"$name\" in this Application");
    }


}